import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components'
import classnames from 'classnames'
import Iconfont from '@/components/Iconfont'
import { staticUrl } from '@/utils'
import { connect } from 'react-redux'
import { updateShareLog } from '@/api/distribution'
import GoodsItem from '../components/goods-item'
import { getCheapGoodsList, getAreaInfo, getCheapView } from '@/api/cheap'
import { AtDrawer } from 'taro-ui'
import './index.scss'

interface State {
  list: any,
  currentSelect: any,
  cityList: any,
  pMobile: '',
  ppMobile: '',
  mobile: '',
  shareShow: false,
  authInfo: {},
  loading: true,
  show: false,
  location: {},
  details: {},
  shareImg: '',
  storeCode: '',
  pUnionId: '',
  ppUnionId: '',
  thirdPartyShareSource: ''
}

export default class CheapIndex extends Component<any, any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      list: [],
      cityList: [],
      currentSelect: {},
      pMobile: '',
      ppMobile: '',
      mobile: '',
      shareShow: false,
      authInfo: {},
      loading: true,
      show: false,
      location: {},
      details: {},
      shareImg: '',
      storeCode: '',
      pUnionId: '',
      ppUnionId: '',
      thirdPartyShareSource: ''
    }
  }

  state: State

  async componentDidMount() {
    let { pMobile = '', ppMobile = '', storeCode, pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = this.$instance.router.params
    this.setState({
      pMobile,
      ppMobile,
      pUnionId,
      ppUnionId,
      storeCode,
      thirdPartyShareSource
    }, () => {
      this.getAreaInfo()
    })
  }

  getActivityView(index) {
    let { list } = this.state
    // let { jihuasuanId } = list[0]
    console.log('list', list)
    getCheapView({
      id: list[index].jihuasuanId
    }).then(res => {
      list[index] = Object.assign(list[index], {
        shareBodyTitle: res.data.data.shareBodyTitle,
        upload6Url: res.data.data.upload6Url,
        shareHeaderTitle: res.data.data.shareHeaderTitle
      })
      this.setState({
        shareImg: res.data.data.upload6Url || '',
        list
      })
    })
  }

  /**
  * 跳转详情
  **/
  gotoDetails = (item) => {
    console.log('item', item)
    let { pMobile = '', ppMobile = '', storeCode = '', pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = this.state
    Taro.navigateTo({ url: `/pages/cheap/topic/index?id=${item.jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&storeCode=${storeCode}&pUnionId=${pUnionId}&ppUnionId=${ppUnionId}&thirdPartyShareSource=${thirdPartyShareSource}` })
  }

  onShareAppMessage(res) {
    console.log('res', res)
    const USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { list, pMobile, shareImg, pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = this.state
    if (res.from == 'button') { // 来自页面按钮的转发
      let paraams = {
        jihuasuanId: list[res.target.dataset.index].jihuasuanId,
        mobile: USERINFO.mobile,
        pMobile: pMobile,
        pUnionId: pUnionId || '',
        jihuasuanGoodsId: res.target.id,
        thirdPartyShareSource: thirdPartyShareSource || ''
      }
      updateShareLog(paraams)
      return {
        title: list[res.target.dataset.index].shareHeaderTitle || `养车超低价，分享赚佣金`,
        path: `pages/cheap/index/index?jihuasuanId=${list[res.target.dataset.index].jihuasuanId}&pMobile=${USERINFO.mobile}&ppMobile=${pMobile}&ppUnionId=${pUnionId}${thirdPartyShareSource ? `&thirdPartyShareSource=${thirdPartyShareSource}` : ''}`,
        imageUrl: list[res.target.dataset.index].upload6Url,
        bgImgUrl: list[res.target.dataset.index].upload6Url
      }
    } else {
      let paraams = {
        jihuasuanId: list[0].jihuasuanId,
        mobile: USERINFO.mobile,
        pMobile: pMobile || '',
        pUnionId: pUnionId || '',
        thirdPartyShareSource: thirdPartyShareSource || ''
      }
      updateShareLog(paraams)
      return {
        title: list[0].shareHeaderTitle || `养车超低价，分享赚佣金`,
        path: `pages/cheap/index/index?jihuasuanId=${list[0].jihuasuanId}&pMobile=${USERINFO.mobile}&ppMobile=${pMobile}&ppUnionId=${pUnionId}${thirdPartyShareSource ? `&thirdPartyShareSource=${thirdPartyShareSource}` : ''}`,
        imageUrl: list[0].upload6Url,
        bgImgUrl: list[0].upload6Url
      }
    }

  }

  //获取城市
  getAreaInfo() {
    getAreaInfo({ location: '' }).then(res => {
      let data = res.data.data
      let { adCode, districtCode, districtName, name } = data
      this.setState({
        cityList: data,
        currentSelect: {
          adCode, districtCode, districtName, name
        }
      }, () => {
        this.getCheapGoodsList()

      })
    })
  }

  chooseCity = (e) => {
    console.log('e', e)
    this.setState({
      show: false,
      currentSelect: e
    }, () => {
      this.getCheapGoodsList()
    })
  }

  // 筛选城市区域
  selectCity = (e) => {
    e.stopPropagation()
    console.log('执行了吗')
    this.setState({ show: true })
  }

  gotoExtActivityRule(e, id) {
    e.stopPropagation()
    let query = {
      jihuasuanId: id
    }
    Taro.navigateTo({ url: `/pages/webview/index/index?path=/cheap/activity-rule&query=${JSON.stringify(query)}` })
  }



  //获取活动商品
  getCheapGoodsList() {
    let { currentSelect } = this.state
    console.log('currentSelect', currentSelect)
    let params = {
      clientSource: 0,
      cityCode: currentSelect && currentSelect.adCode || '440100'
    }
		this.setState({
			list:[]
		},()=>{
			getCheapGoodsList(params).then(res => {
				let data = res.data.data
				if (data.length) {
					this.setState({
						list: data,
						loading: false,
					}, () => {
						for (var i in data) {
							this.getActivityView(i)
						}
					})
				}
			})
		})

  }

  render() {
    const { list, loading, show, currentSelect, cityList, pMobile = '', ppMobile = '', storeCode = '', shareImg, pUnionId = '', ppUnionId = '', thirdPartyShareSource = '' } = this.state
    return (
      <View className='activity'>
        <View className="ac-bg"></View>
        <View className="activity">
          <View className="list">
            <View className="location"
              onClick={(e) => this.selectCity(e)}>
              <Text className="location-ico"></Text>
              <Text className="location-txt">{currentSelect.name || '广州市'}</Text>
            </View>

            {
              list && list.length > 0 && list.map((item, index) => {
                return (
                  <View onClick={() => this.gotoDetails(item)} className="list-item">
                    <View className='act-rule' onClick={(e) => this.gotoExtActivityRule(e, item.jihuasuanId)}>活动规则</View>
                    <GoodsItem shareData={{
                      pMobile,
                      ppMobile,
                      pUnionId,
                      ppUnionId,
                      storeCode,
                      shareImg,
                      thirdPartyShareSource
                    }} goods={item} index={index}></GoodsItem>
                  </View>
                )
              })
            }
            {
              !loading && list.length == 0 ?
                <View className="no-list">
                  <View className="no-list-tips"></View>
                  <View className="tips-txt">当前城市暂未开放活动。</View>
                </View>
                : null
            }

          </View>
        </View>
        <AtDrawer
          show={show}
          mask
          width={'80%'}
          right={true}
        >
          <View className="city-box">
            <View className="platform-top" >
              当前选择城市：{currentSelect.name || '广州市'}
            </View>
            {
              cityList.list && cityList.list.length > 0 ?
                cityList.list.map((item, index) => {
                  return <View >
                    <View className="letter">{item.firstLetter}</View>
                    {
                      item.items.map((c, ci) => {
                        return <View className="area-name"
                          onClick={() => this.chooseCity(c)} >{c.name}</View>

                      })
                    }
                  </View>
                }) : null
            }

          </View>
        </AtDrawer>
      </View>
    )
  }
}
